package com.dj.mingkong.admin.boot.handler;

import com.dj.mingkong.common.enums.DeleteEnum;
import com.dj.mingkong.common.infrastructure.base.eo.BaseMgEo;
import com.dj.mingkong.common.microservice.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;

import java.time.LocalDateTime;


/**
 * @author zenglonghui
 * @date: 2023/6/29 15:21
 */
@Slf4j
@Configuration
public class MongoCommonFieldsEventListener extends AbstractMongoEventListener<Object> {

    private static final String USER_ID = "user_id";

    @Value("${dj.mybatis.plus.config.devops-field}")
    private String devopsField;
    @Value("${dj.mybatis.plus.config.timestamp-set:false}")
    private boolean timestampSet;

    @Override
    public void onBeforeConvert(BeforeConvertEvent event) {
        log.trace("start insert or update fill......");
        Object source = event.getSource();
        if (source instanceof BaseMgEo entity) {
            if (StringUtils.isBlank(entity.getId())) {
                insertFill(entity);
            } else {
                updateFill(entity);
            }
        }
    }

    private void insertFill(BaseMgEo entity) {
        log.trace("start insert fill......");
        entity.setDeleted(DeleteEnum.NOT.getIntVal());
        if (USER_ID.equals(this.devopsField)) {
            entity.setCreatePerson(this.wrapIdFiled(UserContext.getUserId()));
        }

        if (this.timestampSet) {
            entity.setCreateTime(LocalDateTime.now());
        }
        this.updateFill(entity);
    }

    private void updateFill(BaseMgEo entity) {
        log.trace("start update fill......");
        if (USER_ID.equals(this.devopsField)) {
            entity.setUpdatePerson(UserContext.getUserId());
        }

        if (this.timestampSet) {
            entity.setUpdateTime(LocalDateTime.now());
        }
    }

    private Long wrapIdFiled(Long id) {
        return id == null ? 0L : UserContext.getUserId();
    }

}
